#ifndef PLUGINMANAGER_H
#define PLUGINMANAGER_H
#include <QApplication>
#include <QPluginLoader>
#include <QDir>
#include <QDebug>
#include <QtDesigner/QDesignerCustomWidgetCollectionInterface>
#include <QLibraryInfo>

class PluginManager : public QObject
{
    Q_OBJECT

public:
    void loadDesignerPlugins(const QString &modleName )
    {
        QStringList pluginPaths;
        pluginPaths << QApplication::applicationDirPath() + "/plugins/"+modleName;
        pluginPaths << QDir::currentPath() + "/plugins/"+modleName;
        //designer
        pluginPaths << QLibraryInfo::location(QLibraryInfo::PluginsPath) + "/designer/"+modleName;
        qDebug() << pluginPaths ;
        foreach (const QString &path, pluginPaths) {
            QDir pluginDir(path);
            if (!pluginDir.exists()) continue;

            QStringList pluginFiles = pluginDir.entryList(
                QStringList() << "*.dll" << "*.so" << "*.dylib",
                QDir::Files
                );

            foreach (const QString &fileName, pluginFiles) {
                loadDesignerPlugin(pluginDir.absoluteFilePath(fileName));
            }
        }
    }

    QList<QDesignerCustomWidgetInterface*> getCustomWidgets() const
    {
        return m_customWidgets;
    }

    QWidget* createWidget(const QString &className, QWidget *parent = nullptr)
    {
        foreach (QDesignerCustomWidgetInterface *widgetInterface, m_customWidgets) {
            if (widgetInterface->name() == className) {
                return widgetInterface->createWidget(parent);
            }
        }
        return nullptr;
    }

private:
    void loadDesignerPlugin(const QString &filePath)
    {
        QPluginLoader loader(filePath);
        QObject *plugin = loader.instance();
        if (!plugin) {
            qDebug() << "Failed to load plugin:" << loader.errorString();
            return;
        }

        // 检查是否是单个自定义控件
        QDesignerCustomWidgetInterface *singleWidget =
            qobject_cast<QDesignerCustomWidgetInterface*>(plugin);
        if (singleWidget) {
            m_customWidgets.append(singleWidget);
            qDebug() << "Loaded single widget:" << singleWidget->name();
            return;
        }

        // 检查是否是控件集合
        QDesignerCustomWidgetCollectionInterface *collection =
            qobject_cast<QDesignerCustomWidgetCollectionInterface*>(plugin);
        if (collection) {
            QList<QDesignerCustomWidgetInterface*> widgets = collection->customWidgets();
            foreach (QDesignerCustomWidgetInterface *widget, widgets) {
                m_customWidgets.append(widget);
                qDebug() << "Loaded widget from collection:" << widget->name();
            }
        }
    }

    QList<QDesignerCustomWidgetInterface*> m_customWidgets;
};

#endif // PLUGINMANAGER_H
